'use strict';

const Service = require('egg').Service;
const AdminUsersModel = require('../../model/AdminUsersModel');
const AdminUserRoleRelModel = require('../../model/AdminUserRoleRelModel');
const AdminUserRightsModel = require('../../model/AdminUserRightsModel');
const adminUsersModel = new AdminUsersModel();
const adminUserRoleRelModel = new AdminUserRoleRelModel();
const adminUserRightsModel = new AdminUserRightsModel();

/**
 * 创建者: rliang
 * 创建时间: 2019年08月19日 22:41:31
 * 功能描述: 用户相关业务处理
 */
class UserService extends Service {

  /**
   * 根据用户名查找用户信息
   * @param {string} uname 用户登录账号
   */
  async getAdminUserByName(uname) {
    // 根据用户名查询用户信息 
    const adminUserInfo = await adminUsersModel.findOneByName(this.app, uname);
    if (adminUserInfo) return adminUserInfo;
    this.logger.debug('查询到的用户信息:', adminUserInfo);
    return null;
  }

  /**
   * 新增管理用户
   * @param {object} adminUser 管理用户信息
   */
  async addAdminUser(adminUser) {
    
    let _adminUser = new adminUsersModel.entity();

    const isHas = await this.getAdminUserByName(adminUser.loginName);
    if (isHas != null) {
      return null;
    }

    const conn = await this.app.mysql.beginTransaction(); // 初始化事务
    try {

      const uid = this.ctx.getUUID(adminUser.loginName);
      _adminUser = adminUser;
      _adminUser.id = uid;
      _adminUser.state = 1;
      _adminUser.creator = this.ctx.curAdminUser.id;
      _adminUser.loginPwd = this.ctx.encryOfMD5(_adminUser.loginPwd);
      _adminUser.createTime = this.ctx.getDate_YYYYMMDDHHmmss();
      _adminUser.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
      await adminUsersModel.insert_transaction(conn, _adminUser);

      const adminUserRoleRel = new adminUserRoleRelModel.entity();
      adminUserRoleRel.adminUserId = uid;
      adminUserRoleRel.roleId = adminUser.roleId;
      adminUserRoleRel.creator = this.ctx.curAdminUser.id;
      adminUserRoleRel.createTime = this.ctx.getDate_YYYYMMDDHHmmss();
      adminUserRoleRel.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();

      await adminUserRoleRelModel.insert_transaction(conn, adminUserRoleRel);

      const adminUserRights = [];
      if (adminUser.userRights && adminUser.userRights.length > 0) {
        for (const userRight of adminUser.userRights) {
          const entity = new adminUserRightsModel.entity();
          entity.userId = adminUser.id;
          entity.menuId = userRight.menuId;
          entity.controller = userRight.controller;
          entity.userRights = userRight.userRights;
          entity.creator = this.ctx.curAdminUser.id;
          entity.createTime = this.ctx.getDate_YYYYMMDDHHmmss();
          entity.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
          adminUserRights.push(entity);
        }

        await adminUserRightsModel.insertBatch_transaction(conn, adminUserRights);
      }

      await conn.commit(); // 提交事务

      return true;
    } catch (err) {
      await conn.rollback(); // 一定记得捕获异常后回滚事务！！
      this.logger.error('更新角色权限失败（操作数据库失败）', err);
      return false;
    }
  }

  /**
   * 删除用户（逻辑删除）
   * @param {string} _id id
   */
  async deleteAdminUser(_id) {
    
    const conn = await this.app.mysql.beginTransaction(); // 初始化事务
    try {
      const _adminUser = new adminUsersModel.entity();
      _adminUser.id = _id;
      _adminUser.state = 0;
      _adminUser.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
      const re = await adminUsersModel.updateById_transaction(conn, _adminUser);

      // const adminUserRoleRel = new adminUserRoleRelModel.entity();
      // adminUserRoleRel.adminUserId = _id;
      // await adminUserRoleRelModel.deleteByUid_transaction(conn, adminUserRoleRel);

      await conn.commit(); // 提交事务

      return true;
    } catch (err) {
      // error, rollback
      await conn.rollback(); // 一定记得捕获异常后回滚事务！！
      this.logger.error('删除用户失败（操作数据库失败）', err);
      return false;
    }
  }

  /**
   * 更新管理用户信息
   * @param {object} request 管理用户
   */
  async updateAdminUser(request) {

    const conn = await this.app.mysql.beginTransaction(); // 初始化事务
    try {
      let adminUser = new adminUsersModel.entity();
      
      adminUser = request;
      // 如果传入密码则需要加密
      if (request.loginPwd) {
        adminUser.loginPwd = this.ctx.encryOfMD5(request.loginPwd);
      }
      adminUser.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
      const re = await adminUsersModel.updateById_transaction(conn, adminUser);

      const adminUserRoleRel = new adminUserRoleRelModel.entity();
      adminUserRoleRel.adminUserId = request.id;
      adminUserRoleRel.roleId = request.roleId;
      adminUserRoleRel.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
      await adminUserRoleRelModel.updateByUid_transaction(conn, adminUserRoleRel);
      
      
      if (request.userRights && request.userRights.length > 0) {

        await adminUserRightsModel.deleteByUserId_transaction(conn, adminUser.id, this.logger);

        const adminUserRights = [];

        for (const userRight of request.userRights) {
          const entity = new adminUserRightsModel.entity();
          entity.userId = adminUser.id;
          entity.menuId = userRight.menuId;
          entity.controller = userRight.controller;
          entity.userRights = userRight.userRights;
          entity.creator = this.ctx.curAdminUser.id;
          entity.createTime = this.ctx.getDate_YYYYMMDDHHmmss();
          entity.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
          adminUserRights.push(entity);
        }

        await adminUserRightsModel.insertBatch_transaction(conn, adminUserRights);
      }

      await conn.commit(); // 提交事务

      return true;
    } catch (err) {
      // error, rollback
      await conn.rollback(); // 一定记得捕获异常后回滚事务！！
      this.logger.error('更新角色权限失败（操作数据库失败）', err);
      return false;
    }
  
  }

  /**
   * 查询用户列表
   * @param {string} loginName 用户账户名
   * @param {string} branchCode 地区
   * @param {int} state 状态
   * @param {int} roleId 角色ID
   * @param {string} startDate 开始时间
   * @param {string} endDate 结束时间
   * @param {int} pageSize 一页多少页
   * @param {int} pageIndex 当前页数
   */
  async queryAdminUsersList(loginName, branchCode, state, roleId, startDate, endDate, pageSize, pageIndex) {
    // 获取用户列表信息
    const results = await adminUsersModel.selectAdminUsersList(this.app, { loginName, branchCode, state, roleId, startDate, endDate, pageSize, pageIndex });
    if (results && results.length > 0) {
      return results;
    } 
    return null;
  }
  
  async queryAdminUsersListCount(loginName, branchCode, state, roleId, startDate, endDate) {
    return await adminUsersModel.selectAdminUsersListCount(this.app, { loginName, branchCode, state, roleId, startDate, endDate });
  }
  
  async queryAdminUserRightsByUserId(userId) {
    return await adminUserRightsModel.selectUserRightsByUserId(this.app, userId);
  }

  async findByIdAdminUserInfo(userId) {
    const adminUserInfo = await adminUsersModel.findByIdAdminUserInfo(this.app, userId);
    
    if (adminUserInfo) {
      const userRights = await adminUserRightsModel.selectUserRightsByUserId(this.app, userId);
      adminUserInfo.userRights = userRights;
    }

    return adminUserInfo;
  }

  async updatePwd(id, loginPwd) {
    const models = {
      login_pwd: this.ctx.encryOfMD5(loginPwd),
    };
    return await adminUsersModel.updatePwd(this.app, id, models);
  }
}

module.exports = UserService;
